package com.guigu.base.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.base.entity.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.base.entity.dto.GlobalUserDTO;
import com.guigu.base.entity.dto.TransportTripsDto;
import com.guigu.base.entity.dto.TruckDto;
import com.guigu.base.entity.vo.*;
import com.guigu.base.mapper.TransportLineMapper;
import com.guigu.base.service.*;
import com.guigu.common.utils.Constant;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 线路表 服务实现类
 * </p>
 *
 * @author TaoLong
 * @since 2021-11-08
 */
@Service
public class TransportLineServiceImpl extends ServiceImpl<TransportLineMapper, TransportLine> implements TransportLineService {

    private TransportTripsService transportTripsService;
    private TruckService truckService;

    private TruckDriverService truckDriverService;

    private CoreOrgService coreOrgService;

    private TransportTripsTruckDriverService transportTripsTruckDriverService;

    private GlobalUserService userService;

    public TransportLineServiceImpl(TransportTripsService transportTripsService, TruckService truckService, TruckDriverService truckDriverService, CoreOrgService coreOrgService, TransportTripsTruckDriverService transportTripsTruckDriverService, GlobalUserService userService) {
        this.transportTripsService = transportTripsService;
        this.truckService = truckService;
        this.truckDriverService = truckDriverService;
        this.coreOrgService = coreOrgService;
        this.transportTripsTruckDriverService = transportTripsTruckDriverService;
        this.userService = userService;
    }

    @Override
    public TransportLine saveTransportLine(TransportLine TransportLine) {
        baseMapper.insert(TransportLine);
        return TransportLine;
    }

    @Override
    public IPage<TransportLine> findByPage(Integer page, Integer pageSize, String lineNumber, String name,
                                           String transportLineTypeId) {
        Page<TransportLine> iPage = new Page(page, pageSize);
        LambdaQueryWrapper<TransportLine> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(name)) {
            lambdaQueryWrapper.like(TransportLine::getName, name);
        }
        if (StringUtils.isNotEmpty(lineNumber)) {
            lambdaQueryWrapper.like(TransportLine::getLineNumber, lineNumber);
        }
        if (StringUtils.isNotEmpty(transportLineTypeId)) {
            lambdaQueryWrapper.eq(TransportLine::getTransportLineTypeId, transportLineTypeId);

        }
        lambdaQueryWrapper.eq(TransportLine::getStatus, Constant.DATA_DEFAULT_STATUS);
        lambdaQueryWrapper.orderBy(true, false, TransportLine::getId);
        return baseMapper.selectPage(iPage, lambdaQueryWrapper);
    }

    @Override
    public List<TransportLine> findAll(List<String> ids, String agencyId, List<String> agencyIds) {
        LambdaQueryWrapper<TransportLine> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (ids != null && ids.size() > 0) {
            lambdaQueryWrapper.in(TransportLine::getId, ids);
        }
        if (StringUtils.isNotEmpty(agencyId)) {
            lambdaQueryWrapper.eq(TransportLine::getAgencyId, agencyId);
        }
        if (agencyIds != null && agencyIds.size() > 0) {
            lambdaQueryWrapper.in(TransportLine::getAgencyId, agencyIds);
        }
        lambdaQueryWrapper.eq(TransportLine::getStatus, Constant.DATA_DEFAULT_STATUS);
        lambdaQueryWrapper.orderBy(true, false, TransportLine::getId);
        return baseMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public void disable(String id) {
        TransportLine TransportLine = new TransportLine();
        TransportLine.setId(id);
        TransportLine.setStatus(Constant.DATA_DISABLE_STATUS);
        baseMapper.updateById(TransportLine);
    }

    /**
     * 根据id查找线路
     *
     * @param id       线路Id
     * @param truckId  车辆Id
     * @param driverId 司机Id
     * @param tripsId  车次Id
     * @return
     */
    @Override
    public R<TransportLineVO> findTransportLineVOById(String id, String truckId, String driverId, String tripsId) {
        TransportLineVO transportLineVO = new TransportLineVO();
        if (StringUtils.isNotBlank(id)) {
            /**
             * 获取线路信息
             */
            TransportLine t = this.baseMapper.selectById(id);

            BeanUtils.copyProperties(t, transportLineVO);
            /**
             * 获取车次信息
             */
            if (ObjectUtils.isNotEmpty(transportLineVO)) {
                /**
                 * 获取车次信息
                 */
                TransportTripsVO tripsVO = getTransportTripsVO(tripsId, transportLineVO);
                /**
                 * 获取车辆信息
                 */
                getTruck(truckId, tripsVO);
                /**
                 * 获取司机信息
                 */
                getTruckDriver(driverId, tripsVO);

                /**
                 * 设置进线路信息
                 */
                transportLineVO.setTransportTripsVO(tripsVO);
                return new R<>(ResultCode.SUCCESS_CODE, transportLineVO);
            }
        }
        return new R<>(ResultCode.ERROR_CODE, null);
    }

    /**
     * 查询全部线路信息
     *
     * @return
     */
    @Override
    public R<List<TransportLineVO>> queryAll() {
        List<TransportLine> lineList = baseMapper.selectList(null);
        List<TransportLineVO> list = lineList.stream().map(l -> {
            TransportLineVO transportLineVO = new TransportLineVO();
            BeanUtils.copyProperties(l, transportLineVO);
            if (ObjectUtils.isNotEmpty(transportLineVO)) {
                if (StringUtils.isNotBlank(transportLineVO.getStartAgencyId())) {
                    CoreOrg startAgency = coreOrgService.getById(transportLineVO.getStartAgencyId());
                    transportLineVO.setStartAgency(startAgency);
                }
                if (StringUtils.isNotBlank(transportLineVO.getEndAgencyId())) {
                    CoreOrg endAgency = coreOrgService.getById(transportLineVO.getEndAgencyId());
                    transportLineVO.setEndAgency(endAgency);
                }
            }
            return transportLineVO;
        }).collect(Collectors.toList());
        return new R<>(ResultCode.SUCCESS_CODE, list);
    }

    /**
     * 根据车次Id查询出车辆,司机
     *
     * @param id 车次Id
     * @return
     */
    @Override
    public R<List<TransportTripsDto>> findTransportTripsById(String id) {
        QueryWrapper<TransportTripsTruckDriver> t = new QueryWrapper<>();
        t.eq("transport_trips_id", id);
        List<TransportTripsTruckDriver> driverList = transportTripsTruckDriverService.list(t);
        List<TransportTripsDto> list = new ArrayList<>();
        if (CollUtil.isNotEmpty(driverList)) {
            list = driverList.stream().map(l -> {
                TransportTripsDto dto = new TransportTripsDto();
                /**
                 * 查询车次信息
                 */
                if (StringUtils.isNotBlank(l.getTransportTripsId())) {
                    TransportTrips trips = transportTripsService.getById(l.getTransportTripsId());
                    BeanUtils.copyProperties(trips, dto);
                }
                /**
                 * 查询车辆信息
                 */
                if (StringUtils.isNotBlank(l.getTruckId())) {
                    Truck truck = truckService.getById(l.getTruckId());
                    TruckDto truckDto = new TruckDto();
                    BeanUtils.copyProperties(truck, truckDto);
                    dto.setTruckDto(truckDto);
                }
                /**
                 * 查询司机信息
                 */
                if (StringUtils.isNotBlank(l.getUserId())) {
                    GlobalUser user = userService.getById(l.getUserId());
                    GlobalUserDTO globalUserDTO = new GlobalUserDTO();
                    BeanUtils.copyProperties(user, globalUserDTO);
                    dto.setGlobalUserDTO(globalUserDTO);
                }
                return dto;
            }).collect(Collectors.toList());

        }
        return new R<>(ResultCode.SUCCESS_CODE, list);
    }

    @Override
    public R<List<TransportLineDashboardVO>> getLineDashboard() {
        List<TransportLine> lineList = list(null);
        List<TransportLineDashboardVO> list = lineList.stream().map(l -> {
            TransportLineDashboardVO transportLineDashboardVO = new TransportLineDashboardVO();
            CoreOrg startAgency = coreOrgService.getById(l.getStartAgencyId());
            CoreOrg endAgency = coreOrgService.getById(l.getEndAgencyId());
            if (ObjectUtils.isNotEmpty(startAgency)) {
                transportLineDashboardVO.setStartAgency(startAgency);
            }
            if (ObjectUtils.isNotEmpty(endAgency)) {
                transportLineDashboardVO.setEndAgency(endAgency);
            }
            return transportLineDashboardVO;
        }).collect(Collectors.toList());
        return new R<>(ResultCode.SUCCESS_CODE, list);
    }

    /**
     * 获取车次信息
     *
     * @param tripsId
     * @param transportLineVO
     * @return
     */
    @NotNull
    private TransportTripsVO getTransportTripsVO(String tripsId, TransportLineVO transportLineVO) {
        TransportTripsVO tripsVO = new TransportTripsVO();
        if (StringUtils.isNotBlank(tripsId)) {
            QueryWrapper<TransportTrips> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("transport_line_id", transportLineVO.getId());
            queryWrapper.eq("id", tripsId);
            TransportTrips trips = transportTripsService.getOne(queryWrapper);

            if (ObjectUtils.isNotEmpty(trips)) {
                BeanUtils.copyProperties(trips, tripsVO);
                if (ObjectUtils.isNotEmpty(tripsVO)) {
                    tripsVO.setName(transportLineVO.getName());
                }
            }
        }

        return tripsVO;
    }

    /**
     * 获取车辆信息
     *
     * @param truckId
     * @param tripsVO
     */
    private void getTruck(String truckId, TransportTripsVO tripsVO) {
        if (StringUtils.isNotBlank(truckId)) {
            /**
             * 获取车辆信息
             */
            Truck truck = truckService.getById(truckId);
            if (ObjectUtils.isNotEmpty(truck)) {
                TruckVO truckVO = new TruckVO();
                BeanUtils.copyProperties(truck, truckVO);
                tripsVO.setTruckVO(truckVO);
            }
        }
    }

    /**
     * 获取司机信息
     *
     * @param driverId
     * @param tripsVO
     */
    private void getTruckDriver(String driverId, TransportTripsVO tripsVO) {
        if (StringUtils.isNotBlank(driverId)) {
            /**
             * 获取司机信息
             */
            QueryWrapper<TruckDriver> q = new QueryWrapper<>();
            q.eq("user_id", driverId);
            TruckDriver driver = truckDriverService.getOne(q);
            if (ObjectUtils.isNotEmpty(driver)) {
                TruckDriverVO truckDriverVO = new TruckDriverVO();
                BeanUtils.copyProperties(driver, truckDriverVO);
                tripsVO.setTruckDriverVO(truckDriverVO);
            }
        }
    }
}
